package com.starblink.android.basic.widget.refresher

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieDrawable
import com.scwang.smart.refresh.layout.api.RefreshHeader
import com.scwang.smart.refresh.layout.api.RefreshKernel
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.constant.RefreshState
import com.scwang.smart.refresh.layout.constant.SpinnerStyle
import com.starblink.android.basic.extension.dp2px

@SuppressLint("RestrictedApi")
class SKRefreshHeader constructor(val context: Context) : RefreshHeader {

    private val lottieView: LottieAnimationView = LottieAnimationView(context).apply {
        layoutParams = FrameLayout.LayoutParams(100.dp2px(), 50.dp2px()).also {
            it.gravity = Gravity.CENTER
        }
        setAnimation("lottie/refresh_2.json")
        repeatCount = LottieDrawable.INFINITE
        repeatMode = LottieDrawable.RESTART
    }

    private val view: View

    init {
        view = FrameLayout(context).apply {
            layoutParams = ViewGroup.MarginLayoutParams(
                ViewGroup.MarginLayoutParams.MATCH_PARENT,
                100.dp2px()
            )
            addView(lottieView)
        }
    }

    override fun onStateChanged(
        refreshLayout: RefreshLayout,
        oldState: RefreshState,
        newState: RefreshState
    ) {
        when (newState) {
            RefreshState.PullDownToRefresh, RefreshState.ReleaseToRefresh, RefreshState.Refreshing, RefreshState.RefreshReleased, RefreshState.RefreshFinish -> {
                if (lottieView.isAnimating.not()) {
                    lottieView.playAnimation()
                }
            }
            else -> {
                lottieView.pauseAnimation()
            }
        }
    }

    override fun getView(): View = view

    override fun getSpinnerStyle(): SpinnerStyle = SpinnerStyle.Translate

    override fun setPrimaryColors(vararg colors: Int) {
    }

    override fun onInitialized(kernel: RefreshKernel, height: Int, maxDragHeight: Int) {
    }

    override fun onMoving(
        isDragging: Boolean,
        percent: Float,
        offset: Int,
        height: Int,
        maxDragHeight: Int
    ) {
    }

    override fun onReleased(refreshLayout: RefreshLayout, height: Int, maxDragHeight: Int) {

    }

    override fun onStartAnimator(refreshLayout: RefreshLayout, height: Int, maxDragHeight: Int) {

    }

    override fun onFinish(refreshLayout: RefreshLayout, success: Boolean): Int = 1000

    override fun onHorizontalDrag(percentX: Float, offsetX: Int, offsetMax: Int) {
    }

    override fun isSupportHorizontalDrag(): Boolean = false
}